package com.book.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.book.entity.vo.UserVo;
import com.book.exception.GlobalException;
import com.book.utils.JwtUtils;
import com.book.utils.MD5;
import com.book.utils.PageUtils;
import com.book.utils.Query;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.book.dao.UserDao;
import com.book.entity.UserEntity;
import com.book.service.UserService;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Value("${aliyun.msm.file.keyid}")
    private String keyId;
    @Value("${aliyun.msm.file.keysecret}")
    private String keysecret;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Resource
    private UserDao userDao;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public boolean sendMsm(String photo, Map<String, Object> param) {

        if(StringUtils.isEmpty(photo)){
            return false;
        }

        DefaultProfile profile =
                DefaultProfile.getProfile("default", keyId, keysecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", photo);
        request.putQueryParameter("SignName", "我的天下在线教育网站");
        request.putQueryParameter("TemplateCode", "SMS_199590303");
        request.putQueryParameter("TemplateParam",  JSONObject.toJSONString(param)); //验证码数据，转换json数据传递
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return false;
    }


    @Override
    public void saveUser(UserVo user) {
        if(user == null
                || StringUtils.isEmpty(user.getUsername())
                || StringUtils.isEmpty(user.getPassword())
                || StringUtils.isEmpty(user.getEmail())
                || StringUtils.isEmpty(user.getPhoto())) {
            throw new GlobalException(500, "请完善信息！！");
        }
        String verificationCode = redisTemplate.opsForValue().get("Photo_" + user.getPhoto());

        if(StringUtils.isEmpty(verificationCode) || !verificationCode.equals(user.getVerificationCode())){
            throw new GlobalException(500, "验证码错误！！");
        }

        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());

        Integer userCount = userDao.selectCount(queryWrapper);
        if(userCount > 0){
            throw new GlobalException(500, "用户已存在！！");
        }

        user.setPassword(MD5.encrypt(user.getPassword()));
        user.setShowStatus(1);

        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(user,userEntity);
        userDao.insert(userEntity);


    }

    @Override
    public String login(UserVo userVo) {

        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userVo.getUsername());
        queryWrapper.eq("password",MD5.encrypt(userVo.getPassword()));
        UserEntity userEntity = userDao.selectOne(queryWrapper);
        if(userEntity == null){
            throw new GlobalException(500,"账号或密码错误！！");
        }
         return JwtUtils.getJwtToken(userEntity.getId().toString(),userEntity.getUsername());

    }

}